package com.example.hetong_system.controller;

import com.example.hetong_system.model.Customer;
import com.example.hetong_system.model.Employee;
import com.example.hetong_system.model.ResponseResult;
import com.example.hetong_system.model.SystemAdmin;
import com.example.hetong_system.model.dto.LoginRequest;
import com.example.hetong_system.repository.CustomerRepository;
import com.example.hetong_system.repository.EmployeeRepository;
import com.example.hetong_system.repository.SystemAdminRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private EmployeeRepository employeeRepository;

    @Autowired
    private SystemAdminRepository systemAdminRepository;

    // 员工注册
    @PostMapping("/register/employee")
    public ResponseEntity<?> registerEmployee(@RequestBody Employee employee) {
        try {
            // 这里应该调用AuthService的注册方法
            // authService.registerEmployee(employee);
            employeeRepository.save(employee);
            return ResponseEntity.ok("员工注册成功");
        } catch (Exception e) {
            return ResponseEntity.status(500).body("注册失败：" + e.getMessage());
        }
    }

    // 管理员注册
    @PostMapping("/register/admin")
    public ResponseEntity<?> registerAdmin(@RequestBody SystemAdmin admin) {
        try {
            // authService.registerAdmin(admin);
            systemAdminRepository.save(admin);
            return ResponseEntity.ok("管理员注册成功");
        } catch (Exception e) {
            return ResponseEntity.status(500).body("注册失败：" + e.getMessage());
        }
    }

    @PostMapping("/register/customer")
    public ResponseEntity<?> registerCustomer(@RequestBody Customer customer) {
        try {
            // authService.registerCustomer(customer);
            customerRepository.save(customer);
            return ResponseEntity.ok("客户注册成功");
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.status(500).body("注册失败：" + e.getMessage());
        }
    }

    @PutMapping("/admin/change-password")
    public ResponseEntity<?> changePassword(
            @RequestParam String username,
            @RequestParam String oldPassword,
            @RequestParam String newPassword) {

        Optional<SystemAdmin> adminOptional = systemAdminRepository.findByUsernameAndPassword(username, oldPassword);

        if (!adminOptional.isPresent()) {
            return ResponseEntity.badRequest().body("原密码错误");
        }

        SystemAdmin admin = adminOptional.get();
        admin.setPassword(newPassword); // 更新密码
        systemAdminRepository.save(admin); // 保存到数据库

        return ResponseEntity.ok("密码修改成功");
    }


    /**
     * 验证验证码
     */
    @GetMapping("/verify-code")
    public ResponseEntity<ResponseResult> verifyCode(
            @RequestParam String code,
            HttpServletRequest request) {
        // 从Session中获取生成的验证码
        String sessionCode = (String) request.getSession().getAttribute("code");

        boolean isVerifySuccess = sessionCode != null && sessionCode.equalsIgnoreCase(code);

        if (isVerifySuccess) {
            // 验证成功后清除session中的验证码，防止重复使用
            request.getSession().removeAttribute("code");
            return ResponseEntity.ok(ResponseResult.success("验证码验证成功"));
        } else {
            return ResponseEntity.ok(ResponseResult.error("验证码错误"));
        }
    }

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest request, HttpServletRequest httpRequest) {
        try {
            logger.info("接收到登录请求: {}", request);

            String username = request.getUsername();
            String password = request.getPassword();
            String role = request.getRole().toLowerCase();
            String verifyCode = request.getVerifyCode();

            // 验证验证码
            String sessionCode = (String) httpRequest.getSession().getAttribute("code");
            logger.info("验证码验证: 输入={}, 存储={}", verifyCode, sessionCode);

            if (sessionCode == null || !sessionCode.equalsIgnoreCase(verifyCode)) {
                httpRequest.getSession().removeAttribute("code");
                return ResponseEntity.badRequest()
                        .body(ResponseResult.error("验证码错误", "verifyCode"));
            }

            // 验证通过后清除验证码
            httpRequest.getSession().removeAttribute("code");
            logger.info("验证码验证通过");

            // 根据角色验证用户
            Map<String, Object> response = new HashMap<>();
            if ("customer".equals(role)) {
                Optional<Customer> customer = customerRepository.findByContactNameAndPassword(username, password);
                if (customer.isPresent()) {
                    response.put("message", "顾客登录成功");
                    response.put("role", "customer");
                    response.put("user", customer.get());
                    return ResponseEntity.ok(response);
                }
            } else if ("employee".equals(role)) {
                Optional<Employee> employee = employeeRepository.findByNameAndPassword(username, password);
                if (employee.isPresent()) {
                    response.put("message", "员工登录成功");
                    response.put("role", "employee");
                    response.put("user", employee.get());
                    return ResponseEntity.ok(response);
                }
            } else if ("admin".equals(role)) {
                Optional<SystemAdmin> admin = systemAdminRepository.findByUsernameAndPassword(username, password);
                if (admin.isPresent()) {
                    response.put("message", "管理员登录成功");
                    response.put("role", "admin");
                    response.put("user", admin.get());
                    return ResponseEntity.ok(response);
                }
            } else {
                return ResponseEntity.badRequest().body("角色错误");
            }

            return ResponseEntity.status(401).body("用户名或密码错误");
        } catch (Exception e) {
            logger.error("登录处理异常", e);
            return ResponseEntity.status(500).body("服务器错误: " + e.getMessage());
        }
    }
}